const express = require('express');
const router = express.Router();
const { Setting } = require('../../models');  
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');


//id占位查询
router.get('/', async function(req, res, next) {
    try{
        const setting = await getSetting(req)
        success(res,'success', setting,201)
    }catch(err){
        failure(res,err)
    }
});

//修改系统设置
router.put('/', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const setting = await getSetting(req)
        await setting.update(body)
        success(res,'success', {
            status: true,
            msg: '更新成功',
            data:{setting}
        },200)
    }catch(err){
        failure(res,err)
    }
})


const bodyFilter = ['name','icp','copyright','createdAt','updatedAt']
function filterBody(body) {
    const result = {}
    bodyFilter.forEach(key => {
        if(body[key]){
            result[key] = body[key]
        }
    })
    return result
}
async function getSetting() {
    const setting = await Setting.findOne()
    
    if( !setting ) throw new NotFoundError(`系统设置不存在`)
    return setting
}
module.exports = router;
